package com.smartscreen.contentmanage.controller;

import com.smartscreen.contentmanage.entity.ClassMoment;
import com.smartscreen.contentmanage.service.ClassMomentService;
import com.smartscreen.common.response.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/content/classes")
@Validated
public class ClassMomentController {
    
    @Autowired
    private ClassMomentService classMomentService;
    
    /**
     * 创建班级动态
     * @param classId 班级ID
     * @param moment 动态内容
     * @return 创建结果
     */
    @PostMapping("/{classId}/moments")
    public ApiResponse<Map<String, String>> createMoment(
            @PathVariable @NotBlank String classId,
            @RequestBody @Valid ClassMoment moment) {
        
        try {
            if (classId == null || classId.trim().isEmpty()) {
                return ApiResponse.badRequest("班级ID不能为空");
            }
            
            moment.setClassId(classId);
            moment.setStatus("pending"); // 默认待审核
            boolean success = classMomentService.save(moment);
            
            if (success) {
                Map<String, String> data = new HashMap<>();
                data.put("momentId", moment.getMomentId());
                return ApiResponse.created("发布成功，等待审核", data);
            } else {
                return ApiResponse.serverError("发布失败");
            }
        } catch (Exception e) {
            return ApiResponse.serverError("发布失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取班级动态列表
     * @param classId 班级ID
     * @return 动态列表
     */
    @GetMapping("/{classId}/moments")
    public ApiResponse<List<ClassMoment>> getMoments(@PathVariable @NotBlank String classId) {
        try {
            if (classId == null || classId.trim().isEmpty()) {
                return ApiResponse.badRequest("班级ID不能为空");
            }
            
            List<ClassMoment> moments = classMomentService.getMomentsByClassId(classId);
            
            if (moments == null || moments.isEmpty()) {
                return ApiResponse.success("暂无班级动态", moments);
            }
            
            return ApiResponse.success("获取班级动态成功", moments);
        } catch (Exception e) {
            return ApiResponse.serverError("获取班级动态失败：" + e.getMessage());
        }
    }
}